/**
 * @Date: 2022-04-05 19:47:55
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-04-16 10:16:20
 * @FilePath: \weibo-api\app.js
 * @Description: app
 */
// @ts-nocheck
const { SESSION_SCRET_KEY, REDIS_CONF } = require("./conf/db");
const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const koabody = require("koa-body");
const redisStore = require("koa-redis");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const session = require("koa-generic-session");
const path = require("path");
const koaStatic = require("koa-static");
//路由引入
const index = require("./routes/index");
const users = require("./routes/users");
const blogs = require("./routes/blogs");
const topics = require("./routes/topics");

//错误监听
onerror(app);
app.use(koaStatic(path.join(__dirname, "public")));
// 中间件
// app.use(bodyparser({
//   enableTypes: ['json', 'form', 'text']
// }))
app.use(
  koabody({
    multipart: true,
    formidable: {
      uploadDir: path.join(__dirname, "/public/uploads"),
      keepExtensions: true,
    },
  }),
);
app.use(json());
app.use(logger());
app.use(require("koa-static")(__dirname + "/public"));
app.use(
  views(__dirname + "/views", {
    extension: "pug",
  }),
);

// 访问日志打印
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
//session配置
app.keys = [SESSION_SCRET_KEY];
app.use(
  session({
    key: "weibo.sid",
    prefix: "weibo:sess:",
    //配置cookie
    cookie: {
      path: "/",
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000,
    },
    store: redisStore({
      all: `${REDIS_CONF.host}:${REDIS_CONF.port}`,
    }),
  }),
);
// 路由
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());
app.use(blogs.routes(), blogs.allowedMethods());
app.use(topics.routes(), topics.allowedMethods());

// 错误信息处理
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;
